package pubM

import (
	"encoding/json"
	"errors"
	"fmt"
	"db2s/arg"
	"db2s/conn"
	"db2s/ref"
	"os"
)

type Conn struct {
	Source conn.ConEr
	Target conn.ConEr
}

func InitDSnsPool(m arg.ConfigParameter) (db Conn, err error) {
	var res []conn.ConEr
	var event = "[InitDSnsPool]"
	defer func() {
		if r := recover(); r != nil {
			err = errors.New(fmt.Sprintf("defer recover An exception was captured. abnormal is %v ", r))
		}
	}()
	for k, v := range []conn.ConText{m.SecondaryL.DSnsV.SourceConnText, m.SecondaryL.DSnsV.TargetConnText} {
		var ll conn.ConEr
		if ll, err = conn.NewConn(v.Name); err != nil || ll == nil {
			err = ref.ErrAddPrintf(event, err)
			return
		}
		var val []byte
		if val, err = json.Marshal(v); err != nil {
			err = ref.ErrAddPrintf(event, err)
			return
		}
		if err = ll.Set("conText", val); err != nil {
			err = ref.ErrAddPrintf(event, err)
			return
		}
		if err = ll.Set("mode", m.SecondaryL.RulesV.CheckMode); err != nil {
			err = ref.ErrAddPrintf(event, err)
			return
		}
		if m.SecondaryL.RulesV.Sync.WriteParameterOpt && k == 1 {
			if err = ll.Optimize(); err != nil {
				err = ref.ErrAddPrintf(event, err)
				return
			}
		}
		if err = ll.Open(); err != nil {
			err = ref.ErrAddPrintf(event, err)
			return
		}
		res = append(res, ll)
	}
	db.Source = res[0]
	db.Target = res[1]
	return
}

func UpdateModifyParameterSync(conn conn.ConEr, file *os.File) (err error) {
	var event = "[UpdateModifyParameterSync]"
	defer func() {
		if err = file.Close(); err != nil {
			return
		}
	}()
	defer func() {
		if r := recover(); r != nil {
			err = errors.New(fmt.Sprintf("defer recover An exception was captured. abnormal is %v ", r))
		}
	}()
	var record [][]byte
	if record, err = conn.GetOptimizeRecord(); err != nil {
		err = ref.ErrAddPrintf(event, err)
		return
	}
	for _, v := range record {
		if _, err = file.WriteString(fmt.Sprintf("%v\n", string(v))); err != nil {
			err = ref.ErrAddPrintf(event, err)
			return
		}
	}
	return
}
